﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using VSLangProj;
using theeg.DependencyAnalysis.CommonAddin.Models;

namespace theeg.DependencyAnalysis.VsAddin2012
{
    public class VsProject : IProject
    {
        private readonly EnvDTE.Project _dteProject;

        public string Name { get; set; }
        public bool IsSelected { get; set; }
        public bool IsClr { get { return IsClrProject(_dteProject); } }
        public string OutputFileName { get { return GetAssemblyPath(_dteProject); } }

        public VsProject(EnvDTE.Project project)
        {
            _dteProject = project;
        }

        public static bool IsClrProject(EnvDTE.Project project)
        {
            var clrTokens = new HashSet<string> { "B77A5C561934E089", "B03F5F7F11D50A3A", "31BF3856AD364E35" };
            var vsproject = project.Object as VSProject;
            if (vsproject != null)
            {
                return vsproject.References.Cast<Reference>().Any(reference => clrTokens.Contains(reference.PublicKeyToken));
            }
            return false;
        }

        static string GetAssemblyPath(EnvDTE.Project vsProject)
        {
            try
            {
                if (vsProject.Properties == null) return string.Empty;
                string fullPath = vsProject.Properties.Item("FullPath").Value.ToString();
                string outputPath = vsProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
                string outputDir = Path.Combine(fullPath, outputPath);
                string outputFileName = vsProject.Properties.Item("OutputFileName").Value.ToString();
                string assemblyPath = Path.Combine(outputDir, outputFileName);
                fullPath = Path.GetFullPath(assemblyPath);
                if (File.Exists(fullPath)) return fullPath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
            return string.Empty;
        }

    }
}